package com.change.service.system;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.change.core.page.Page;
import com.change.dto.req.QuerySystemRoleReq;
import com.change.dto.req.SaveSystemRoleReq;
import com.change.dto.resp.QuerySystemRoleResp;
import com.change.entity.system.SystemRole;
import com.change.exception.BizException;
import com.change.exception.ResultStatus;
import com.change.mapper.system.SystemRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author jhlz
 * @date 2022-08-27
 */
@Slf4j
@Service
public class SystemRoleService extends ServiceImpl<SystemRoleMapper, SystemRole> {
    private final SystemRoleMapper sysRoleMapper;

    public SystemRoleService(SystemRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }

    public Page<List<QuerySystemRoleResp>> getPage(Page page, QuerySystemRoleReq req) {

        return page;
    }

    public QuerySystemRoleResp detail(Integer id) {
        SystemRole sysRole = this.sysRoleMapper.selectById(id);
        SystemRole roleDetail = Optional.ofNullable(sysRole)
                .orElseThrow(() -> new BizException(ResultStatus.Common.NOT_FOUND));
        QuerySystemRoleResp resp = new QuerySystemRoleResp();
        BeanUtil.copyProperties(roleDetail, resp);
        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    public SystemRole save(SaveSystemRoleReq req) {
        SystemRole newRole = new SystemRole();
        BeanUtil.copyProperties(req, newRole);
        return newRole;
    }

    @Transactional(rollbackFor = Exception.class)
    public SystemRole update(SaveSystemRoleReq req) {
        // 查找
        SystemRole role = this.sysRoleMapper.selectById(req.getId());
        BeanUtil.copyProperties(req, role);
        // 更新
        this.sysRoleMapper.updateById(role);
        return role;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {
        return this.sysRoleMapper.deleteById(id);
    }

    /**
     * 获取角色列表
     *
     * @return 角色列表
     */
    public List<SystemRole> getAllRoleList() {
        return this.sysRoleMapper.selectList(null);
    }
}
